﻿using System.Windows;
using System.Diagnostics;
using System.IO.IsolatedStorage;
using Microsoft.Phone.Info;
using Microsoft.Phone.Scheduler;
using SharedAgentLib;
using System;
using System.Collections.Generic;
using DataObjectsPhone;

namespace Agent
{
    public class ScheduledAgent : ScheduledTaskAgent
    {
        private static volatile bool _classInitialized;
        public String BackgroundPNG = "background.png";
        public String MainPageURLForToast = "/MainPage.xaml";
        public String ToastTitle = "Mutex:";
        public String AppName = "SampleApp1";

        /// <remarks>
        /// ScheduledAgent constructor, initializes the UnhandledException handler
        /// </remarks>
        public ScheduledAgent()
        {
            if (!_classInitialized)
            {
                _classInitialized = true;
                // Subscribe to the managed exception handler
                Deployment.Current.Dispatcher.BeginInvoke(delegate
                {
                    Application.Current.UnhandledException += ScheduledAgent_UnhandledException;
                });
            }
        }

        /// Code to execute on Unhandled Exceptions
        private void ScheduledAgent_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }

        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {
            Debug.WriteLine("Hi im your agent!!!");

            var locationService = new LocationServices();
            locationService.PositionChanged += locationService_PositionChanged;
            locationService.Start();
            //Debug.WriteLine("SampleAgent.SampleAgent.OnInvoke");

            //IsoStorageData mutex = MutexedIsoStorageFile.Read();

            //if (mutex.checkPoints != null)
            //{
            //    foreach (CheckPoint point in mutex.checkPoints)
            //    {
            //        if (point.Done == false)
            //        {
            //            point.Done = true;
            //        }
            //    }
            //}

            //MutexedIsoStorageFile.Write(mutex);

            //ToastNotifications.ShowToast(ToastTitle, "Checkpoint checked!", MainPageURLForToast);

            ////Tile Pinned to Start screen (processname + datetime in minutes)
            //// "2" signifies sampleagent
            //TileNotifications.UpdateTile("CheckPoint Checked", BackgroundPNG, 2);

            //// this makes the agent run in a shorter cycle than 30 minutes
            //// if the iso data setting is turned off (from the app)
            //if (mutex.CycleAgentEveryMinute)
            //{
            //    AgentMgr.RunDebugAgent();
            //}
        }

        void locationService_PositionChanged(object sender, LocationChangeEventArgs e)
        {
            CheckCheckPoints(e.Location.Location);
            ((LocationServices)sender).Stop();

            NotifyComplete();
        }

        private void CheckCheckPoints(System.Device.Location.GeoCoordinate geoCoordinate)
        {
            IsoStorageData mutex = MutexedIsoStorageFile.Read();
            if (mutex.checkPoints != null)
            {
                var isUpdated = false;
                foreach (CheckPoint point in mutex.checkPoints)
                {
                   isUpdated = point.CheckLocation(geoCoordinate) || isUpdated;
                }
                if (isUpdated)
                {
                    MutexedIsoStorageFile.Write(mutex);
                    ToastNotifications.ShowToast(ToastTitle, "Checkpoint checked!", MainPageURLForToast);

                    //Tile Pinned to Start screen (processname + datetime in minutes)
                    // "2" signifies sampleagent
                    TileNotifications.UpdateTile("CheckPoint Checked", BackgroundPNG, 2);
                }
                else
                {
                    ToastNotifications.ShowToast(ToastTitle, "No match!", MainPageURLForToast);
                }
            }
        }
    }
}